#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <json/json.h>
#include "vedio.h"
#include <stdlib.h>
#include "motor.h"
const char* ip="47.121.24.16";
uint16_t port=8000;
int main()
{
    printf("aaa\n");
  int sockfd=socket(AF_INET,SOCK_STREAM,0);//create tcp and server
   if(sockfd<0)
   {

    printf("socket error\n");


   }
   printf("bb\n");
   //建立连接
   struct sockaddr_in aliserver;
   socklen_t len=sizeof(aliserver);

   aliserver.sin_family=AF_INET;
   aliserver.sin_addr.s_addr=inet_addr(ip);
   aliserver.sin_port=htons(port);


   if(connect(sockfd,(const struct sockaddr*)&aliserver,len)<0)
   {
        
      printf("connect error\n");
      exit(-1);

   }
   printf("cc\n");
   //发送信息给服务器通知服务器摄像头号
   struct json_object*obj=(struct json_object*)json_object_new_object();
   json_object_object_add(obj,"cmd",json_object_new_string("info"));
   json_object_object_add(obj,"deviceid",json_object_new_string("0001"));

   const char*s=json_object_to_json_string(obj);
   if(send(sockfd,s,strlen(s),0)<0)
   {
       printf("send error\n");
       exit(-2);

   }
   printf("dd\n");
   //接收服务器的端口号信息(用于udp发送视频数据)//
   char buffer[256];
   if(recv(sockfd,buffer,sizeof(buffer),0)<0)
   {
    
      printf("recv error");
      exit(-3);



   }
    printf("ee\n");
   struct json_object*json =json_tokener_parse(buffer);
   struct json_object*cmd,*port;
   uint16_t serverport;
   cmd=json_object_object_get(json,"cmd");
   port=json_object_object_get(json,"port");

   if(!strcmp((const char*)json_object_get_string(cmd),"port_info"))
   {
       serverport=json_object_get_int(port);//获取到服务器端口号

   }


   pthread_t tid;
   pthread_create(&tid,NULL,send_data,&serverport);

   printf("ff\n");
  while(1)
  {
     memset(buffer,0,sizeof(buffer));
     if(recv(sockfd,buffer,sizeof(buffer),0)<0)
   {
    
      printf("recv error");
      exit(-4);
   }
       struct json_object*json =json_tokener_parse(buffer);
      struct json_object*cmd,*action;
      cmd=json_object_object_get(json,"cmd");
      action=json_object_object_get(json,"action");
      if(!strcmp((const char*)json_object_get_string(cmd),"control"))
      {    
           const char*act=json_object_get_string(action);
           if(!strcmp(act,"left"))
           {motor_left();  }
           else if(!strcmp(act,"right"))
           {motor_right();}
           else if(!strcmp(act,"up"))
           {motor_up();}
           else if(!strcmp(act,"down"))
           {motor_down();}
      }

    
  }


   return 0;


}
